import api from '@/common/request/index.js'
const state = {
	list: [],
	data: {
		show: false,
		area: [{}],
		count: 0,
		selectAddress: ['请选择'],
		selectIndex: [],
		nameList: [],
	},
	info: {
		id: '',
		show: false,
		address: '',
		place: '',
		mobile: '',
		name: '',
		is_default: 0
	},
	selected: {}, //选择的地址
}
const mutations = {
	set_selected(state,payload) {
		state.selected = payload
	},
	set_data(state, payload) {
		for(let key in payload) {
			state.data[key] = payload[key]
		}
	},
	
	set_info(state, payload) {
		state.info = payload;
	},
	
	set_list(state, payload) {
		state.list.push(payload)
		state.list.sort((a,b)=>{
			return b.show - a.show;
		})
		state.info = {}		//清空数据
	},
	set_show(state,payload) {
		let index = payload.index
		state.list[index].show = payload.show
	},
	
	set_edit(state,payload) {
		state.info = payload
	},
	
	set_editlist(state,payload) {
		state.list.map((item,index) => {
			if (item.id == payload.id) {
				state.list[index] = payload.info
			}
		})
		state.list.sort((a,b)=>{
			return b.show - a.show;
		})
	}
}
const actions = {
	//获取选中的地址
	get_selected({commit},payload) {
		commit('set_selected',payload)
	},
	
	//获取地址选择器中的信息
	get_data({commit}, payload) {
		commit('set_data',payload)
	},
	
	//获取地址信息
	get_info({commit}, payload) {
		commit('set_info', payload)
	},
	
	//添加地址
	get_list({commit}, payload) {
		commit('set_list', payload)
	},
	
	//修改默认地址
	get_show({commit}, payload) {
		commit('set_show',payload)
	},
	
	//获得修改的地址信息
	get_edit({commit},payload) {
		commit('set_edit',payload)
	},
	//保存修改地址
	get_editlist({commit},payload) {
		commit('set_editlist',payload)
	},
	// 收货地址
	get_Place({commit, ...a}, payload) {
		  return new Promise((resolve, reject) => {
			  api('memberaddress', payload).then(res => {
				  state.list = res.data
				  state.list.sort((a,b)=>{
				  	return b.is_default - a.is_default;
				  })
			  })
		  })
	},
	get_PlaceS({commit, ...a}, payload) {
	    state.list = payload
	    state.list.sort((a,b)=>{
	    return b.is_default - a.is_default;
	   })
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
